<template>
  <Dialog
    :title="title"
    :fullscreen="true"
    :model-value="visible"
    width="700px"
    maxHeight="380px"
    :before-close="closeForm"
  >
    <Form
      :schema="schema"
      :model="company"
      @register="formRegister"
      label-width="120px"
      :isCol="false"
      :rules="rules"
    />
    <template #footer>
      <el-space>
        <BaseButton type="primary" @click="save">保存</BaseButton>
        <BaseButton @click="resetForm">重置</BaseButton>
      </el-space>
    </template>
  </Dialog>
</template>
<script>
import * as companyApi from '@/api/base/company'
import { HrEnumDic } from '@/config/publicDic'
import { Form } from '@/components/Form'
import { Dialog } from '@/components/Dialog'
import { useForm } from '@/hooks/web/useForm'
const { formRegister, formMethods } = useForm()
export default {
  components: {
    Dialog,
    Form
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: null
    },
    companys: {
      type: Array,
      default: null
    }
  },
  data() {
    return {
      title: '新增公司',
      source: null,
      company: {},
      trees: [],
      schema: [],
      rules: {
        FullName: [
          {
            required: true,
            message: '公司全称不能为空！',
            trigger: 'blur'
          }
        ],
        CompanyType: [
          {
            required: true,
            message: '公司类型不能为空！',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {},
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.reset()
        }
      },
      immediate: true
    }
  },
  methods: {
    formRegister,
    initScheme() {
      this.schema = [
        {
          field: 'FullName',
          label: '公司全称',
          component: 'Input',
          componentProps: {
            maxlength: 100,
            placeholder: '公司全称'
          }
        },
        {
          field: 'ShortName',
          label: '公司简称',
          component: 'Input',
          componentProps: {
            maxlength: 50,
            placeholder: '公司简称'
          }
        },
        {
          field: 'CompanyType',
          label: '公司类型',
          component: 'EnumItem',
          componentProps: {
            dicKey: HrEnumDic.companyType,
            placeholder: '公司类型',
            on: {
              change: (val) => {
                this.company.CompanyType = val
                this.loadTrees()
              }
            }
          }
        },
        {
          field: 'ParentId',
          label: '所属父级公司',
          component: 'TreeSelect',
          componentProps: {
            placeholder: '所属父级公司',
            data: this.trees,
            nodeKey: 'value',
            renderAfterExpand: false,
            checkStrictly: true,
            defaultExpandAll: true,
            emitPath: false,
            disabled: this.company.CompanyType == null || this.company.CompanyType == 0,
            clearable: true
          }
        },
        {
          field: 'Address',
          label: '地址',
          component: 'Input',
          componentProps: {
            maxlength: 50,
            placeholder: '地址'
          }
        },
        {
          field: 'Contacts',
          label: '联系人',
          component: 'Input',
          componentProps: {
            maxlength: 20,
            placeholder: '联系人'
          }
        },
        {
          field: 'Telephone',
          label: '联系电话',
          component: 'Input',
          componentProps: {
            maxlength: 30,
            placeholder: '联系电话'
          }
        }
      ]
    },
    async save() {
      const data = await formMethods.validate()
      if (data == null) {
        return
      } else if (this.id) {
        this.set(data)
      } else {
        this.add(data)
      }
    },
    async set(data) {
      await companyApi.Set(this.id, data)
      this.$message({
        message: '更新成功!',
        type: 'success'
      })
      this.$emit('update:visible', false)
      this.$emit('close', true)
    },
    async add(data) {
      await companyApi.Add(data)
      this.$message({
        message: '添加成功!',
        type: 'success'
      })
      this.$emit('update:visible', false)
      this.$emit('close', true)
    },
    async reset() {
      this.loadTrees()
      if (this.id == null) {
        this.title = '新增公司'
        this.source = null
        this.company = {}
      } else {
        const data = await companyApi.Get(this.id)
        if (data.ParentId == 0) {
          data.ParentId = null
        }
        this.source = data
        this.company = Object.assign({}, data)
        this.title = '编辑公司:' + data.FullName + '信息'
      }
      this.initScheme()
      formMethods.setValues(this.company)
    },
    isNull(str) {
      return str == null || str === ''
    },
    loadTrees() {
      const list = []
      this.companys.forEach((c) => {
        const item = {
          value: c.Id,
          label: this.isNull(c.ShortName) ? c.FullName : c.ShortName,
          children: this.getChildren(c),
          disabled:
            (c.CompanyType === 0 && this.company.CompanyType === 0) ||
            (this.id != null && this.id === c.id)
        }
        list.push(item)
      })
      this.trees = list
    },
    getChildren(c) {
      if (c.Children == null || c.Children.length === 0) {
        return null
      }
      const list = []
      c.Children.forEach((a) => {
        if (a.CompanyType === 2) {
          return
        }
        list.push({
          value: a.Id,
          label: this.isNull(a.ShortName) ? a.FullName : a.ShortName,
          children: this.getChildren(a),
          disabled: this.id != null && this.id === c.id
        })
      })
      return list.length === 0 ? null : list
    },
    closeForm() {
      this.$emit('update:visible', false)
      this.$emit('close', false)
    },
    resetForm() {
      if (this.id == null) {
        this.company = {}
      } else {
        this.company = Object.assign({}, this.source)
      }
      formMethods.setValues(this.company)
    }
  }
}
</script>
